package cc.opcol.iot.app.web;

import cc.opcol.iot.app.AppConfiguration;
import cc.opcol.iot.app.auth.UserSessionService;
import cc.opcol.iot.app.vo.OpcolError;
import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebFilter(urlPatterns = "/*")
public class SecurityFilter implements Filter {

    private final static Logger logger = LoggerFactory.getLogger(SecurityFilter.class);

    @Autowired
    AppConfiguration appConfiguration;

    @Autowired
    UserSessionService userSessionService;

    Gson gson=new Gson();

    private String[] urlPattens=new String[]{};

    private boolean initialized=false;

    public void init() throws ServletException {
        String cUrlPattens=appConfiguration.getAuthUrlPatterns();
        urlPattens= StringUtils.split(cUrlPattens,",");
        for(int i=0;i<urlPattens.length;i++){
            if(urlPattens[i].endsWith("/*")){
                urlPattens[i]=urlPattens[i].substring(0,urlPattens[i].length()-1);
            }
        }
        initialized=true;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse reps = (HttpServletResponse) response;
        reps.setHeader("Access-Control-Allow-Origin", "*");
        reps.setHeader("Access-Control-Allow-Credentials","true");
        reps.setHeader("Access-Control-Allow-Headers","accessKey,Content-Type");
        if(!initialized){
            init();
        }
        String uri=req.getRequestURI();
        if(!appConfiguration.isUrlAuth()){
            filterChain.doFilter(request, response);
            return;
        }
        if(!isNeedAuth(uri)){
            filterChain.doFilter(request, response);
            return;
        }

        String timestamp=req.getParameter("timestamp");
        String signature=req.getParameter("signature");
        String appId=req.getParameter("appid");
        if(!StringUtils.isBlank(appId)){
            if(!userSessionService.validate(appId,timestamp,signature)) {
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/json; charset=utf-8");
                Map<String,String> map = new HashMap<>();
                response.getWriter().write(gson.toJson(new ResourceVo(OpcolError.AUTHENTICATION_FAILED,"Authentication failed")));
                return;
            }
            filterChain.doFilter(request,response);
            return;
        }

        String accessKey=req.getParameter("accessKey");
        if(StringUtils.isBlank(accessKey)){
            accessKey=getAccessKeyCookies(req);
        }
        if(StringUtils.isBlank(accessKey)){
            accessKey=req.getHeader("accessKey");
        }
        if(!userSessionService.validateAccessKey(accessKey)){
            response.getWriter().write(gson.toJson(new ResourceVo(OpcolError.AUTHENTICATION_FAILED,"Authentication failed")));
            return;
        }
//        if(!userSessionService.validate(accessKey,timestamp,signature)){
//            reps.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//            reps.sendRedirect(appConfiguration.getLoginUrl());
//            return;
//        }
       filterChain.doFilter(request, response);
    }

    private String getAccessKeyCookies(HttpServletRequest req) {
        if(req.getCookies()==null){
            return "";
        }
        for(Cookie cookie :req.getCookies()){
            if(cookie.getName().equals("accessKey")){
                return cookie.getValue();
            }
        }
        return "";
    }

    private boolean isNeedAuth(String uri) {
        for(String up:urlPattens){
            if(up.equals("/")){
                return true;
            }
            if(uri.startsWith(up)){
                return true;
            }

        }
        return false;
    }

    @Override
    public void destroy() {

    }
}
